package action;

import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Cart;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

import service.SaleordersService;
import vo.Customer;
import vo.Payment;
import vo.Product;
import vo.Saleorder;
import vo.Saleorderitem;
import vo.Saleordershow;
import vo.Salereturn;
import vo.Salereturnitem;
import vo.User;
import vo.Receipt;




public class SaleordersAction extends ActionSupport{
	protected SaleordersService saleordersService;
	public Saleorder saleorder;
    public Saleorderitem saleorderitem;
    public Product product;
    public double quantity;
    public int rows;
	public int page;
	public String order;
	public String sort;
	public int id;
	public String keyword;
	protected String keyname;
	protected String startdate;
	protected String enddate;
	
	
	
	public void getSaleorders() throws Exception{
		/*System.out.println(keyword);
		System.out.println(keyname);
		System.out.println(startdate);
		System.out.println(enddate);
		if(keyword!=""){
			System.out.println(keyname);
		}*/
		/*if(!startdate.isEmpty()&&!enddate.isEmpty()){
			System.out.println("test");
		SimpleDateFormat myFmt1=new SimpleDateFormat("yyyy-MM-dd"); 
		Date date1 = myFmt1.parse(startdate);
		Date date2 = myFmt1.parse(enddate);
		if(date1.compareTo(date2)>0){
			System.out.println("开始时间大于结束时间了");
		}
		}*/
    	List saleorders = saleordersService.getSaleorders(page, rows, order, sort,keyname,keyword,startdate,enddate);
    	List allSaleorders = saleordersService.browseSaleorders(keyname,keyword,startdate,enddate);
		int total = allSaleorders.size();
		/*List saleordersAfter = new ArrayList();*/
		for(Iterator it = saleorders.iterator();it.hasNext();){
			Saleorder saleorder = (Saleorder)it.next();
			saleorder.setCustomerName(saleorder.getCustomer().getCustomerName());
			if(saleorder.getPayment()!=null){
				saleorder.setPayDatetime(saleorder.getPayment().getCreateDatetime());
				saleorder.setUsername(saleorder.getPayment().getUser().getUsername());
			}else{
				saleorder.setUsername("未付款");
			}
			if(saleorder.getSalereturns().size()!=0){
				double returnTotalprice=0;
				for(Iterator it2 = saleorder.getSalereturns().iterator();it2.hasNext();){
					Salereturn salereturn = (Salereturn)it2.next();
					returnTotalprice = salereturn.getTotalPrice()+returnTotalprice;
				}
				returnTotalprice = new BigDecimal(returnTotalprice).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
				saleorder.setReturnPrice(returnTotalprice);
			}else{
				saleorder.setReturnPrice(0.0);
			}
			/*saleordersAfter.add(product);*/
		}
		this.toBeJson(saleorders, total);
    }
	public void toBeJson(List list,int total) throws Exception{  
        HttpServletResponse response = ServletActionContext.getResponse();  
        HttpServletRequest request = ServletActionContext.getRequest();  
        JSONObject jobj = new JSONObject();//new一个JSON  
        jobj.put("total",total);
        /*jobj.accumulate("total",total );//total代表一共有多少数据 */
		JsonConfig config = new JsonConfig();
         config.setExcludes(new String[]{/*"producttype",*/"customer","payment","saleorderitems","salereturns"});//除去emps属性
         /*config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);*/
         JSONArray json = JSONArray.fromObject(list, config);
		/*JSONArray rows =JSONArray.fromObject(list);
		System.out.println(rows.toString());*/
         jobj.accumulate("rows", json);
		/*jobj.put("rows", list);*/
       /* jobj.accumulate("rows", list);//row是代表显示的页的数据 */
        response.setCharacterEncoding("utf-8");//指定为utf-8  
        response.getWriter().write(jobj.toString());//转化为JSOn格式    
   }  
	public void payAfter() throws IOException{
		Payment payment = new Payment();
		Saleorder getsaleorder = saleordersService.getSaleorder(saleorder.getSaleorderId());
    	payment.setAmount((double)getsaleorder.getSaleorderitems().size());
    	Date date = new Date();    
    	SimpleDateFormat myFmt1=new SimpleDateFormat("yyMMddHHmmss"); 
    	payment.setCreateDatetime(new Timestamp(date.getTime()));
    	payment.setPaymentMethod(1);
    	payment.setSaleorder(getsaleorder);
    	java.util.Map<String, Object> session=ActionContext.getContext().getSession();
    	User user = (User)session.get("user");
    	payment.setUser(user);
    	String paymentNo = myFmt1.format(date)+"-"+String.format("%03d", user.getUserId());
    	payment.setPaymentNo(paymentNo);
    	saleordersService.savePayment(payment);
    	getsaleorder.setState(1);
    	saleordersService.updateSaleorder(getsaleorder);
    	
    	
    	Saleorder getsaleorderForR = saleordersService.getSaleorder(saleorder.getSaleorderId());
    	List saleorderitemsForR = saleordersService.getSaleorderitems(saleorder.getSaleorderId());
    	List receipts = new ArrayList();
		for(Iterator it = saleorderitemsForR.iterator();it.hasNext();){
			Saleorderitem saleorderitem = (Saleorderitem)it.next();
			if(saleorderitem.getQuantity()!=0){
			Receipt receipt = new Receipt();
			receipt.setPrice(saleorderitem.getPrice());
			receipt.setProductName(saleorderitem.getProduct().getProductName());
			receipt.setProductPrice(saleorderitem.getProduct().getPrice());
			receipt.setQuantity(saleorderitem.getQuantity());
			receipts.add(receipt);
			}
		}
		HttpServletResponse response = ServletActionContext.getResponse();  
        HttpServletRequest request = ServletActionContext.getRequest();  
		JSONObject jobj = new JSONObject();//new一个JSON  
        jobj.put("success",true);
        jobj.put("msg","付款成功！！");
        jobj.put("saleorderNo",getsaleorderForR.getSaleorderNo());
        jobj.put("customerName",getsaleorderForR.getCustomer().getCustomerName());
        jobj.put("username",getsaleorderForR.getPayment().getUser().getUsername());
        jobj.put("quantity",getsaleorderForR.getPayment().getAmount());
        jobj.put("discount",getsaleorderForR.getCustomer().getTelephone());
        jobj.put("totalprice",getsaleorderForR.getTotalPrice());
        jobj.put("paytime",getsaleorderForR.getPayment().getCreateDatetime());
        jobj.put("receipts",receipts);
        response.setCharacterEncoding("utf-8");
		response.getWriter().write(jobj.toString());
	}
	public void getSaleorderDetail() throws IOException{
		Saleorder getsaleorderForR = saleordersService.getSaleorder(id);
    	List saleorderitemsForR = saleordersService.getSaleorderitems(id);
    	Set salereturnForR =  getsaleorderForR.getSalereturns();
    	List receipts = new ArrayList();
    	List returnList = new ArrayList();
		for(Iterator it = saleorderitemsForR.iterator();it.hasNext();){
			Saleorderitem saleorderitem = (Saleorderitem)it.next();
			if(saleorderitem.getQuantity()!=0){
			Receipt receipt = new Receipt();
			receipt.setPrice(saleorderitem.getPrice());
			receipt.setProductName(saleorderitem.getProduct().getProductName());
			receipt.setProductPrice(saleorderitem.getProduct().getPrice());
			receipt.setQuantity(saleorderitem.getQuantity());
			receipts.add(receipt);
			}
		}
		for(Iterator it2 = salereturnForR.iterator();it2.hasNext();){
			Salereturn salereturn = (Salereturn)it2.next();
			for(Iterator it3 = salereturn.getSalereturnitems().iterator();it3.hasNext();){
				Salereturnitem salereturnitems = (Salereturnitem)it3.next();
				Receipt receipt1 = new Receipt();
				receipt1.setPrice(salereturnitems.getPrice());
				receipt1.setProductName(salereturnitems.getProduct().getProductName());
				receipt1.setProductPrice(salereturnitems.getProduct().getPrice());
				receipt1.setQuantity(salereturnitems.getQuantity());
				receipt1.setReturnDatetime(salereturn.getCreateDatetime());
				returnList.add(receipt1);
			}
		}
		HttpServletResponse response = ServletActionContext.getResponse();  
        HttpServletRequest request = ServletActionContext.getRequest();  
		JSONObject jobj = new JSONObject();//new一个JSON  
        jobj.put("success",true);
        jobj.put("msg","付款成功！！");
        jobj.put("saleorderNo",getsaleorderForR.getSaleorderNo());
        jobj.put("saleorderCreatetime",getsaleorderForR.getCreateDatetime());
        jobj.put("customerName",getsaleorderForR.getCustomer().getCustomerName());
        if(getsaleorderForR.getPayment()!=null){
        	jobj.put("username",getsaleorderForR.getPayment().getUser().getUsername());
        	jobj.put("paytime",getsaleorderForR.getPayment().getCreateDatetime());
        }else{
        	jobj.put("username","未付款");
        }
        jobj.put("quantity",receipts.size());
        jobj.put("discount",getsaleorderForR.getCustomer().getTelephone());
        jobj.put("totalprice",getsaleorderForR.getTotalPrice());
        jobj.put("receipts",receipts);
        jobj.put("returnList",returnList);
        response.setCharacterEncoding("utf-8");
		response.getWriter().write(jobj.toString());
	}
	public void saleLoadOrder() throws IOException{
		java.util.Map<String, Object> session=ActionContext.getContext().getSession();
    	User user = (User)session.get("user");
    	Cart cart = (Cart)session.get("cart");
    	if(cart!=null){
    		session.remove("cart");
    	}
    	Saleorder saleorder = new Saleorder();
    	Date date = new Date();    
    	SimpleDateFormat myFmt1=new SimpleDateFormat("yyMMddHHmmss"); 
    	String saleorderNo = myFmt1.format(date)+"-"+String.format("%03d", user.getUserId());
    	saleorder.setSaleorderNo(saleorderNo);
    	saleorder.setCreateDatetime(new Timestamp(date.getTime()));
    	HttpServletResponse response = ServletActionContext.getResponse();  
        HttpServletRequest request = ServletActionContext.getRequest();  
		JSONObject jobj = new JSONObject();//new一个JSON  
        jobj.put("success",true);
        jobj.put("saleorderNo",saleorder.getSaleorderNo());
        jobj.put("cashierName",user.getUsername());
        jobj.put("cashierId",user.getUserId());
        session.put("saleorder", saleorder);
        response.setCharacterEncoding("utf-8");
		response.getWriter().write(jobj.toString());
	}
	public void saleLoadCustomer() throws IOException{
		Customer customer = saleordersService.getCustomer(id);
		HttpServletResponse response = ServletActionContext.getResponse();  
        HttpServletRequest request = ServletActionContext.getRequest();  
        JSONObject jobj = new JSONObject(); 
		if(customer==null){
			jobj.put("success",false);
		}else{
			jobj.put("success",true);
			jobj.put("customerId",customer.getCustomerId());
			jobj.put("customerName",customer.getCustomerName());
			jobj.put("discount",customer.getTelephone());
		}
		response.setCharacterEncoding("utf-8");
		response.getWriter().write(jobj.toString());
	}
	public void saleGetSaleorderitems() throws IOException{
		java.util.Map<String, Object> session=ActionContext.getContext().getSession();
    	Cart cart = (Cart)session.get("cart");
    	if(cart!=null){
    		List saleordershows = new ArrayList();
    		for(Iterator it = cart.getItems().values().iterator();it.hasNext();){
    			Saleorderitem saleorderitem = (Saleorderitem)it.next();
    			Saleordershow saleordershow = new Saleordershow();
    			saleordershow.setPrice(saleorderitem.getProduct().getPrice());
    			saleordershow.setProductId(saleorderitem.getProduct().getProductId());
    			saleordershow.setProductName(saleorderitem.getProduct().getProductName());
    			saleordershow.setProducttypeName(saleorderitem.getProduct().getProducttype().getProducttypeName());
    			saleordershow.setQuantity(saleorderitem.getQuantity());
    			saleordershow.setTotalprice(new BigDecimal(saleorderitem.getPrice()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
    			saleordershows.add(saleordershow);
    		}
    		HttpServletResponse response = ServletActionContext.getResponse();  
    		HttpServletRequest request = ServletActionContext.getRequest();  
    		JSONObject jobj = new JSONObject();//new一个JSON  
    		jobj.put("rows",saleordershows);
    		response.setCharacterEncoding("utf-8");
    		response.getWriter().write(jobj.toString());
    	}else{
    		List saleordershows = new ArrayList();
    		HttpServletResponse response = ServletActionContext.getResponse();  
            HttpServletRequest request = ServletActionContext.getRequest();  
    		JSONObject jobj = new JSONObject();//new一个JSON  
            jobj.put("rows",saleordershows);
            response.setCharacterEncoding("utf-8");
    		response.getWriter().write(jobj.toString());
    	}
	}
	public void saleaddSaleorderitem() throws IOException{
		HttpServletResponse response = ServletActionContext.getResponse();  
        HttpServletRequest request = ServletActionContext.getRequest();  
        JSONObject jobj = new JSONObject(); 
		Product product = saleordersService.getProduct(id);
		if(product==null){
			jobj.put("success",false);
		}else{
			double quantity=1;
			Saleorderitem saleorderitem = new Saleorderitem();
			saleorderitem.setProduct(product);
			saleorderitem.setQuantity(quantity);
			saleorderitem.setPrice(Math.round(product.getPrice()*quantity * 100) / 100.0);
    	
			java.util.Map<String, Object> session=ActionContext.getContext().getSession();
			Cart cart =(Cart)session.get("cart");
			if(cart==null){
				cart = new Cart();
			}
			cart.addProduct(product.getProductId(),saleorderitem);
			session.put("cart", cart);
			jobj.put("success",true);
			jobj.put("totalprice",cart.getTotalPrice());
			jobj.put("amount",cart.getItems().size());
		}
        response.setCharacterEncoding("utf-8");
		response.getWriter().write(jobj.toString());
	}
	public void salemodifySaleorderitem() throws IOException{
		java.util.Map<String, Object> session=ActionContext.getContext().getSession();
    	Cart cart =(Cart)session.get("cart");
    	Saleorderitem saleorderitem=cart.getItems().get(id);
		if(order.equals("plus")){
			saleorderitem.setPrice(Math.round(saleorderitem.getProduct().getPrice()*(saleorderitem.getQuantity()+1) * 100) / 100.0);
	    	saleorderitem.setQuantity(saleorderitem.getQuantity()+1);
		}else if(order.equals("reduce")){
			saleorderitem.setPrice(Math.round(saleorderitem.getProduct().getPrice()*(saleorderitem.getQuantity()-1) * 100) / 100.0);
	    	saleorderitem.setQuantity(saleorderitem.getQuantity()-1);
		}else if(order.equals("modify")){
			saleorderitem.setPrice(Math.round(saleorderitem.getProduct().getPrice()*(quantity) * 100) / 100.0);
	    	saleorderitem.setQuantity(quantity);
		}
		HttpServletResponse response = ServletActionContext.getResponse();  
        HttpServletRequest request = ServletActionContext.getRequest();  
        JSONObject jobj = new JSONObject(); 
        jobj.put("success",true);
        jobj.put("totalprice",cart.getTotalPrice());
        jobj.put("amount",cart.getItems().size());
        response.setCharacterEncoding("utf-8");
		response.getWriter().write(jobj.toString());
	}
	public void saleremoveSaleorderitem() throws IOException{
		java.util.Map<String, Object> session=ActionContext.getContext().getSession();
    	Cart cart =(Cart)session.get("cart");
    	cart.getItems().remove(id);
    	HttpServletResponse response = ServletActionContext.getResponse();  
        HttpServletRequest request = ServletActionContext.getRequest();  
        JSONObject jobj = new JSONObject(); 
        jobj.put("success",true);
        jobj.put("totalprice",cart.getTotalPrice());
        jobj.put("amount",cart.getItems().size());
        response.setCharacterEncoding("utf-8");
		response.getWriter().write(jobj.toString());
	}
	public void saleclearSaleorderitem() throws IOException{
		java.util.Map<String, Object> session=ActionContext.getContext().getSession();
		session.remove("cart");
		HttpServletResponse response = ServletActionContext.getResponse();  
        HttpServletRequest request = ServletActionContext.getRequest();  
        JSONObject jobj = new JSONObject(); 
        jobj.put("success",true);
        response.setCharacterEncoding("utf-8");
		response.getWriter().write(jobj.toString());
	}
	public void salecheckout() throws IOException{
		java.util.Map<String, Object> session=ActionContext.getContext().getSession();
    	Cart cart = (Cart)session.get("cart");
    	Customer customer = saleordersService.getCustomer(id);
    	Date date = new Date();    
    	SimpleDateFormat myFmt1=new SimpleDateFormat("yyMMddHHmmss"); 
    	Saleorder saleorder = (Saleorder)session.get("saleorder");;
    	saleorder.setCustomer(customer);
    	saleorder.setState(1);
    	saleorder.setTotalPrice(quantity);
    	for(Iterator item = cart.getItems().values().iterator();item.hasNext();){
    		Saleorderitem saleorderitem = (Saleorderitem)item.next();
    		saleorderitem.setSaleorder(saleorder);
    		saleorder.getSaleorderitems().add(saleorderitem);
    	}
    	Payment payment = new Payment();
    	payment.setAmount((double)cart.getItems().size());
    	payment.setCreateDatetime(new Timestamp(date.getTime()));
    	payment.setPaymentMethod(1);
    	payment.setSaleorder(saleorder);
    	User user = (User)session.get("user");
    	payment.setUser(user);
    	String paymentNo = myFmt1.format(date)+"-"+String.format("%03d", user.getUserId());
    	payment.setPaymentNo(paymentNo);
    	saleorder.setPayment(payment);
    	saleordersService.save(saleorder);
    	HttpServletResponse response = ServletActionContext.getResponse();  
        HttpServletRequest request = ServletActionContext.getRequest();  
        JSONObject jobj = new JSONObject(); 
        jobj.put("success",true);
        jobj.put("paytime",new Timestamp(date.getTime()));
        response.setCharacterEncoding("utf-8");
		response.getWriter().write(jobj.toString());
	}
	public void salesaveOrder() throws IOException{
		java.util.Map<String, Object> session=ActionContext.getContext().getSession();
    	Cart cart = (Cart)session.get("cart");
    	Customer customer = saleordersService.getCustomer(id);
    	Date date = new Date();    
    	SimpleDateFormat myFmt1=new SimpleDateFormat("yyMMddHHmmss"); 
    	Saleorder saleorder = (Saleorder)session.get("saleorder");;
    	saleorder.setCustomer(customer);
    	saleorder.setState(2);
    	saleorder.setTotalPrice(quantity);
    	for(Iterator item = cart.getItems().values().iterator();item.hasNext();){
    		Saleorderitem saleorderitem = (Saleorderitem)item.next();
    		saleorderitem.setSaleorder(saleorder);
    		saleorder.getSaleorderitems().add(saleorderitem);
    	}
    	saleordersService.save(saleorder);
    	HttpServletResponse response = ServletActionContext.getResponse();  
        HttpServletRequest request = ServletActionContext.getRequest();  
        JSONObject jobj = new JSONObject(); 
        jobj.put("success",true);
        jobj.put("saleorderNo",saleorder.getSaleorderNo());
        response.setCharacterEncoding("utf-8");
		response.getWriter().write(jobj.toString());
	}
	
	
	
	
	
	
	
	
	
	public String getKeyname() {
		return keyname;
	}
	public void setKeyname(String keyname) {
		this.keyname = keyname;
	}
	public String getEnddate() {
		return enddate;
	}
	public void setEnddate(String enddate) {
		this.enddate = enddate;
	}
	public String getStartdate() {
		return startdate;
	}
	public void setStartdate(String startdate) {
		this.startdate = startdate;
	}
	public String getKeyword() {
		return keyword;
	}
	public void setKeyword(String keyword) {
		this.keyword = keyword;
	}
	public String getOrder() {
		return order;
	}
	public void setOrder(String order) {
		this.order = order;
	}
	public String getSort() {
		return sort;
	}
	public void setSort(String sort) {
		this.sort = sort;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public int getRows() {
		return rows;
	}
	public void setRows(int rows) {
		this.rows = rows;
	}
	public int getPage() {
		return page;
	}
	public void setPage(int page) {
		this.page = page;
	}
    public double getQuantity() {
		return quantity;
	}
	public void setQuantity(double quantity) {
		this.quantity = quantity;
	}

	public Product getProduct() {
		return product;
	}
	public void setProduct(Product product) {
		this.product = product;
	}
	public Saleorderitem getSaleorderitem() {
		return saleorderitem;
	}

	public void setSaleorderitem(Saleorderitem saleorderitem) {
		this.saleorderitem = saleorderitem;
	}

	public Saleorder getSaleorder() {
		return saleorder;
	}

	public void setSaleorder(Saleorder saleorder) {
		this.saleorder = saleorder;
	}
	public SaleordersService getSaleordersService() {
		return saleordersService;
	}
	public void setSaleordersService(SaleordersService saleordersService) {
		this.saleordersService = saleordersService;
	}
}